package com.peng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.domain.ResponseResult;
import com.peng.domain.dto.AddTagDto;
import com.peng.domain.dto.EditTagDto;
import com.peng.domain.dto.TagListDto;
import com.peng.domain.entity.Category;
import com.peng.domain.entity.Tag;
import com.peng.domain.vo.PageVo;
import com.peng.domain.vo.TagVo;
import com.peng.enums.AppHttpCodeEnum;
import com.peng.exception.SystemException;
import com.peng.service.TagService;
import com.peng.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/content/tag")
public class TagController {

    @Autowired
    private TagService tagService;

    @GetMapping("/list")
    public ResponseResult<PageVo> list(Integer pageNum, Integer pageSize, TagListDto tagListDto){
        return tagService.pageTagList(pageNum,pageSize,tagListDto);
    }

    @PostMapping
    public ResponseResult add(@RequestBody AddTagDto tagDto){
        if (!StringUtils.hasText(tagDto.getName())){
            throw new SystemException(AppHttpCodeEnum.TAG_ISNOTNULL);
        }
        if (NameExist(tagDto.getName())){
            throw new SystemException(AppHttpCodeEnum.TAG_EXIST);
        }
        Tag tag = BeanCopyUtils.copyBean(tagDto, Tag.class);
        tagService.save(tag);
        return ResponseResult.okResult();
    }
    @DeleteMapping("/{id}")
    public ResponseResult delete(@PathVariable("id") Long id){
        tagService.removeById(id);
        return ResponseResult.okResult();
    }
    @GetMapping("/{id}")
    public ResponseResult getById(@PathVariable("id") Long id){
        Tag tag = tagService.getById(id);
        return ResponseResult.okResult(tag);
    }

    @PutMapping
    public ResponseResult Edit(@RequestBody EditTagDto editTagDto){
        if (!StringUtils.hasText(editTagDto.getName())){
            throw new SystemException(AppHttpCodeEnum.TAG_ISNOTNULL);
        }
        if (NameExist(editTagDto.getName())){
            throw new SystemException(AppHttpCodeEnum.TAG_EXIST);
        }
        Tag tag = BeanCopyUtils.copyBean(editTagDto, Tag.class);
        tagService.updateById(tag);
        return ResponseResult.okResult();
    }

    @GetMapping("/listAllTag")
    public ResponseResult listAllTag(){
      List<TagVo> list = tagService.listAllTag();
      return ResponseResult.okResult(list);
    }
    private boolean NameExist(String name) {
        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Tag::getName, name);
        int count = tagService.count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }
}
